<template>
  <div>
    <el-popover
      ref="popoverRef"
      v-model="visible"
      placement="bottom"
      width="400"
      popper-class="preset-filter-popover"
      trigger="click"
      @hide="handleClose">
      <div class="preset-filter">
        <div class="title-container">
          <Title title="快捷筛选" />
          <PlainCreateBtn style="margin-top: -8px" @click="createNew">新建</PlainCreateBtn>
        <!-- <div class="title-btn">
          <div class="cancel-btn" @click="setDefault()">取消默认</div>
          <div :class="{'is-disabled': !selectValueResult || selectValueResult.length === 0}" class="button-text btn" @click="setData">保存当前筛选</div>
        </div> -->
        </div>
        <div :style="editMode.id?{paddingBottom: '56px'}:''" class="main">
          <template v-if="(curPageConfig && curPageConfig.length) || computedPreset.length">
            <div v-for="(page, index) in [...computedPreset, ...curPageConfig]" :class="{'is-default': page.default}" :key="index">
              <div v-if="!isEdit(page.id)" class="preset-item preset-item-hover">
                <div class="label-container">
                  <ToolTip
                    :content="page.filterName || handelText(page.labelList).shortText"
                    :tool-tip="handelText(page.labelList).longText"
                    :label-style="{color: '#333'}"
                    dangerously-use-html
                    is-can-click
                    @handelClick="submit(page)" />
                </div>
                <div v-if="page.default" class="default-tag">默认</div>
                <div class="preset-operate">
                  <div :class="{'disabled': page.isFixed}" class="edit-button flex-center" @click="toSetEditMode(page)">
                    <img :src="EditIcon" width="18" height="18" alt="">
                  </div>
                  <div :class="{'disabled': page.isFixed}" class="edit-button flex-center ml-8" @click="deleteItem(page)">
                    <img :src="DeleteIcon" width="18" height="18" class="operate-icon" alt="">
                  </div>
                </div>
              </div>
              <div v-else class="preset-item">
                <el-input
                  v-model="editMode.name"
                  :maxlength="30"
                  class="item-input"
                  placeholder="请输入名称"
                  size="small" />
                <div :class="{'active': page.default, 'disabled': page.isFixed }" class="flex-center">
                  <div class="label">默认</div>
                  <el-switch :value="page.default" :disabled="page.isFixed" @change="setDefault(page)" />
                </div>
              </div>
            </div>
          </template>
          <div v-else class="empty-center">
            <EmptyPlaceholder text="暂无数据" image-size="80px" empty-img-top="30px" />
          </div>
          <div v-if="editMode.id" class="btn-row">
            <el-button class="ok-btn" type="primary" style="height: 32px;" size="small" @click="toSave()">保存</el-button>
            <el-button class="cancel-btn-style ok-btn" style="height: 32px;" size="small" @click="cancelEdit()">取消</el-button>
          </div>
        </div>
      </div>
      <template v-if="useScopeSlot">
        <slot slot="reference" :visible="visible"/>
      </template>
      <template v-else-if="$slots.default">
        <slot slot="reference" />
      </template>
      <div v-else slot="reference" class="setting-btn"><img :src="settingIcon" alt="">快捷筛选</div>
    </el-popover>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import Title from '@/components/Title';
import { showModal } from '@/utils/message';
import filterIcon from '@/assets/reportManage/open-filter.png';
import deleteIcon from '@/assets/reportManage/delete-filter.png';
import settingIcon from '@/assets/preset-setting.png';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { resource, weibo } from './data';
import EditPresetFilter from './editPresetFilter.vue';
import { handelText } from './util';
import DeleteIcon from '@/assets/config/deleteIcon.png';
import EditIcon from '@/assets/config/editIcon.png';

export default {
  name: 'PresetFilter',
  components: { Title, EmptyPlaceholder, EditPresetFilter },
  props: {
    selectValueResult: {
      type: Array,
      default: null
    },
    getPresetFilter: {
      type: Function,
      default: null
    },
    useScopeSlot: {
      type: Boolean,
      default: false
    },
    isResource: { // 是否资源列表
      type: Boolean,
      default: false
    },
    presetType: { // 预设选项类型, 1-资源, 2-微博效果
      type: Number,
      default: 0
    },
    openHighMode: {
      type: Function,
      default: null
    }
  },
  inject: {
    setPresetVal: { default: null },
    setFilterParams: { default: null },
    getActiveTabs: { default: null },
    getFilterData: { default: null }
  },
  data() {
    return {
      filterIcon, deleteIcon, settingIcon, EditIcon, DeleteIcon,
      visible: false,
      throttled: null,
      editMode: {}
    };
  },
  computed: {
    ...mapState({
      'filterConfig': state => state.filter.filterConfig
    }),
    keyName() {
      const routeName = this.$route.name;
      if (routeName === 'approvalList') {
        const moduleId = this.$route.params.id;
        return routeName + moduleId;
      }
      return routeName;
    },
    curPageConfig() {
      const keyName = this.keyName;
      if (!this.filterConfig || !this.filterConfig[keyName]) return [];
      if (this.getActiveTabs) {
        const activeTabs = this.getActiveTabs();
        return this.filterConfig[keyName].filter(i => {
          if (!i.activeTabs) return true;
          return i.activeTabs === activeTabs;
        });
      }
      return this.filterConfig[keyName];
    },
    computedPreset() {
      if (!this.presetType) { return []; }
      return {
        1: resource,
        2: weibo
      }[this.presetType];
    }
  },
  methods: {
    handelText,
    isEdit(id) {
      return id === this.editMode.id;
    },
    toSetEditMode(item) {
      if (item && item.isFixed) return;
      this.editMode = {
        id: item.id,
        name: item.filterName || ''
      };
    },
    createNew() {
      this.$emit('createNew');
    },
    submit(data) {
      const item = _.cloneDeep(data);
      if (this.setFilterParams) {
        // 如果是资源列表
        this.setFilterParams(item);
      } else {
        // 其他页面
        this.setPresetVal(item.params);
      }
      this.visible = false;
      // 请求查询接口
      this.$emit('queryClick', true);
    },
    cancelEdit() {
      this.editMode = {};
      this.$forceUpdate();
    },
    handleClose() {
      this.editMode = {};
    },
    setResourceData(name) {
      const selectValueResult = _.cloneDeep(this.selectValueResult);
      const presetData = this.getPresetFilter();
      const data = {
        labelList: selectValueResult,
        params: presetData,
        default: false,
        id: new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999)
      };
      if (name) {
        data.filterName = name;
      }
      // 资源列表：有的页面每个tab的筛选项都不一样，所以需要通过 activeTabs 来区分
      if (this.getActiveTabs) {
        const activeTabs = this.getActiveTabs();
        data.activeTabs = activeTabs;
      }
      const keyName = this.keyName;
      const filterConfig = _.cloneDeep(this.filterConfig) || {};
      if (!filterConfig[keyName]) filterConfig[keyName] = [];
      filterConfig[keyName].push(_.cloneDeep(data));
      this.saveFilterConfig(filterConfig);
      ElMessage.success('保存成功');
    },
    setData(name) {
      const selectValueResult = _.cloneDeep(this.selectValueResult);
      if (!selectValueResult || selectValueResult.length === 0) {
        return;
      }
      // 资源列表走这个逻辑，后面的 filterParams 废弃了
      if (this.isResource) {
        this.setResourceData(name);
        return;
      }
      const presetData = this.getPresetFilter();
      const value = _.cloneDeep(presetData.value);
      const filterParams = _.cloneDeep(presetData.filterParams);
      // 渠道单客户名称精准搜索特殊处理
      if (value.exactForClientName === 1 && value.clientName) {
        selectValueResult.forEach(item => {
          if (item.key === 'clientName') {
            item.name += '(精准搜索)';
          }
        });
      }
      if (this.curPageConfig.length >= 15) {
        ElMessage.warning('最多添加15条快捷筛选条件');
        return;
      }
      const data = {
        labelList: selectValueResult,
        params: value,
        default: false,
        id: new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999)
      };

      // 资源才有 getFilterData
      if (this.getFilterData) {
        const filterData = _.cloneDeep(this.getFilterData());
        const keys = filterParams.map(i => i.key);
        const curFilterData = filterData.data.options.filter(i => {
          return keys.includes(i.key);
        });
        const filterObject = {};
        if (curFilterData) {
          const keysList = ['checkedList', 'checkedValue', 'inputend', 'inputstart'];
          curFilterData.forEach(i => {
            Object.keys(i).forEach(k => {
              if (keysList.includes(k)) {
                if (!filterObject[i.key]) filterObject[i.key] = {};
                filterObject[i.key][k] = i[k];
              }
            });
          });
        }
        data.filterObject = filterObject;
      }
      // 资源才有 filterParams，这是独立于资源页面的筛选条件
      if (filterParams && filterParams.length) {
        data.filterParams = filterParams;
      }
      // 资源列表：有的页面每个tab的筛选项都不一样，所以需要通过 activeTabs 来区分
      if (this.getActiveTabs) {
        const activeTabs = this.getActiveTabs();
        data.activeTabs = activeTabs;
      }
      if (name) {
        data.filterName = name;
      }
      const keyName = this.keyName;
      const filterConfig = _.cloneDeep(this.filterConfig) || {};
      if (!filterConfig[keyName]) filterConfig[keyName] = [];
      filterConfig[keyName].push(_.cloneDeep(data));
      this.saveFilterConfig(filterConfig);
      ElMessage.success('保存成功');
      // this.visible = false;
    },
    setDefault(item = null) {
      if (item) this.$set(item, 'default', !item.default);
      this.curPageConfig.forEach(i => {
        if (i.id !== item.id) {
          this.$set(i, 'default', false);
        }
      });
      this.saveFilterConfig(this.filterConfig);
    },
    toSave() {
      if (this.editMode.name) {
        this.curPageConfig.forEach(i => {
          if (i.id === this.editMode.id) {
            this.$set(i, 'filterName', this.editMode.name);
          }
        });
      }
      this.saveFilterConfig(this.filterConfig);
      this.cancelEdit();
    },
    saveFilterConfig(filterConfig) {
      this.$store.dispatch('setFilterConfig', filterConfig);

      // 点击后就调用 `更新`，但1s内超过1次。
      // if (!this.throttled) {
      //   this.throttled = _.throttle(() => {
      //     this.$store.dispatch('setFilterConfig', filterConfig);
      //   }, 1000);
      // }
      // this.throttled();
    },
    handleCloseEdit() {
      setTimeout(() => {
        this.$refs.popoverRef.doShow();
      }, 0);
    },
    deleteItem(item) {
      if (item && item.isFixed) return;
      showModal('是否删除该条快捷筛选？').then(_ => {
        const keyName = this.keyName;
        const index = this.filterConfig[keyName].findIndex(i => i.id === item.id);
        this.filterConfig[keyName].splice(index, 1);
        this.saveFilterConfig(this.filterConfig);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$border-color: #ddd;
$minHeight: 200px;
.setting-btn {
  cursor: pointer;
  font-size: 14px;
  font-weight: 550;
  color: #333333;
  padding: 0 5px;
  height: 28px;
  background: #edeef2;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  img {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}
.preset-filter {
  .title-container {
    display: flex;
    margin-bottom: 4px;
  }
  .main {
    height: $minHeight;
    padding-right: 6px;
    padding-bottom: 12px;
    @include scrollBar($x: hidden, $y: auto, $width: 6px);
  }
}
.ml-8  {
  margin-left: 8px;
}
.label-container {
  display: flex;
  width: 0%;
  flex: 1;
  & ::v-deep {
    .el-tooltip.is-can-click {
      color: #666;
      &:hover {
        color: #406EFF;
      }
    }
  }
}
.default-tag {
  margin-left: 10px;
  font-size: 12px;
  color: #406EFF;
  background-color: #EFF4FF;
  border-radius: 8px;
  flex-shrink: 0;
  padding: 1px 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.edit-button {
  cursor: pointer;
  &.disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}
.preset-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-left: 10px;
  height: 32px;
  line-height: 32px;
  padding-right: 4px;
  .label {
    margin-right: 4px;
  }
}
.preset-item-hover {
  &:hover {
    cursor: pointer;
    background-color: #edeef2;
    font-weight: 600;
    border-radius: 4px;
    &::v-deep {
      .el-tooltip {
        color: #406eff !important;
      }
    }
  }
}
.item-input {
  margin-right: 8px;
  flex: 1;
}
.empty-center {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.preset-operate {
  flex-shrink: 0;
  margin-left: 10px;
  display: flex;
  align-items: center;
}
.footer-btn {
  width: 100%;
}
.btn-row {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px 0;
  background-color: #fff;
  position: absolute;
  bottom: 0;
  width: calc(100% - 34px)
}
</style>
<style lang="scss">
.preset-filter-popover {
  border-radius: 8px !important;
  padding: 16px !important;
}
</style>
